﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

using MINERP.DAL;
using MINERP.ComControls;
using MINERP.COM;
using System.Reflection;


namespace MINERP.CleanupTool
{
    public partial class FrmMain :FrmParent
    {
        private ShowErrMsgHander showErrMsgHander;
        private RefreshStatusHander refreshStatusHander;
        private ShowNotifyMsgHander showNotifyMsgHander;
        private InitProcessBar initProcessBar;

        FrmStatus frmStatus = null;

        Thread th;

        public FrmMain()
        {
            InitializeComponent();
            InitiAuthority();
        }

        /// <summary>
        /// 用户不可用控件的限制
        /// </summary>
        public void InitiAuthority()
        {
            foreach (Control control in this.Controls)
            {
                foreach (string controlName in ControlsName)
                {
                    if (control.Name == controlName)
                    {
                        control.Visible = false;
                    }
                }
            }

            Type t = this.GetType();

            foreach (var item in t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField))
            {

                if (ControlsName.Contains(item.Name))
                {
                    object obj = item.GetValue(this); 
                    if (obj.GetType() == typeof(DevExpress.XtraTab.XtraTabPage))
                    {
                        var it = obj as DevExpress.XtraTab.XtraTabPage;
                        if (it != null)
                        {
                            it.PageVisible = false;
                        }                     
                    }            
                    else
                    {
                        try
                        {
                            var it = obj as Control;
                            if (it != null)
                            {
                                it.Visible = false;
                            }                           
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("无法对该控件进行限制" + ex.Message);
                        }
                    }                    
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            th = new Thread(new ThreadStart(CleanupOrderDataTheadStart));
            //th.IsBackground = true;
        }
        #region 删除生成数据
        private void btnOrderOK_Click(object sender, EventArgs e)
        {
            if (dtStart.DateTime.ToString() == "0001-1-1 0:00:00")
            {
                MessageBox.Show("请选择开始时间","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            if (dtEnd.DateTime.ToString() == "0001-1-1 0:00:00")
            {
                MessageBox.Show("请选择结束时间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (DialogResult.OK == MessageBox.Show("确定删除" + dtStart.DateTime.ToString() + "到"+dtEnd.DateTime.ToString()+"之间的生产数据吗?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                frmStatus = new FrmStatus();
                frmStatus.controlThreadHander = new ControlThreadHander(ControlThread);
                frmStatus.Show();
                th = new Thread(new ThreadStart(CleanupOrderDataTheadStart));
                th.Start();
               
            }
            
        }

        private void CleanupOrderDataTheadStart()
        {
            showErrMsgHander = new ShowErrMsgHander(frmStatus.ShowErrMsg);
            refreshStatusHander = new RefreshStatusHander(frmStatus.SetProcessBar);
            showNotifyMsgHander = new ShowNotifyMsgHander(frmStatus.ShowNotifyMsg);
            initProcessBar = new InitProcessBar(frmStatus.InitProcessBar);
            CleanupData(dtStart.DateTime, dtEnd.DateTime, chkOrder.Checked, chkInnerReturn.Checked, chkMessge.Checked,chkOrderPhoto.Checked,chkPhotoBackup.Checked);
        }
        /// <summary>
        /// 清理数据
        /// </summary>
        /// <param name="datatime"></param>
        /// <param name="isDeleteOrder"></param>
        /// <param name="isDeleteInnerReturn"></param>
        /// <param name="isDeleteChatMessage"></param>
        /// <returns></returns>
        public int CleanupData(DateTime startTime, DateTime endTime, bool isDeleteOrder, bool isDeleteInnerReturn, bool isDeleteChatMessage,bool isdeletePhoto,bool isDeleteBackupPhoto)
        {
            int ret = 0;
            try
            {
                using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
                {
                    List<Tb_OrderBag_BK> orderbagList = null;
                    if (isDeleteOrder)
                    {
                        orderbagList = enty.Tb_OrderBag_BK.Where(o => o.OrderTime <= endTime&&o.OrderTime >=startTime).ToList();
                        SetTotalNum(orderbagList.Count);
                        int currentNum = 0;
                        foreach (var orderbag in orderbagList)
                        {
                            currentNum++;
                            showNotifyMsgHander.Invoke("正在删除订单:" + orderbag.OrderBagId + "......");

                            if (!orderbag.orderInfo_BK.IsLoaded)
                            {
                                orderbag.orderInfo_BK.Load();
                            }
                            initProcessBar.Invoke(orderbag.orderInfo_BK.Count);

                            foreach (var orderInfo in orderbag.orderInfo_BK)
                            {

                                DeletePhotoFolder(orderInfo.OrderPath);
                                refreshStatusHander.Invoke();
                            }
                            enty.DeleteObject(orderbag);
                            try
                            {
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除订单" + orderbag.OrderBagId + "出错");
                            }
                            SetCrrentNum(currentNum);
                        }
                    }
                    else
                    {
                        if (isdeletePhoto)
                        {
                            orderbagList = enty.Tb_OrderBag_BK.Where(o => o.OrderTime <= endTime&&o.OrderTime>=startTime).ToList();
                            SetTotalNum(orderbagList.Count);
                            int currentNum = 0;
                            foreach (var orderbag in orderbagList)
                            {
                                currentNum++;
                                showNotifyMsgHander.Invoke("正在删除订单:" + orderbag.OrderBagId + "......");

                                if (!orderbag.orderInfo_BK.IsLoaded)
                                {
                                    orderbag.orderInfo_BK.Load();
                                }
                                initProcessBar.Invoke(orderbag.orderInfo_BK.Count);

                                foreach (var orderInfo in orderbag.orderInfo_BK)
                                {

                                    DeletePhotoFolder(orderInfo.OrderPath);
                                    refreshStatusHander.Invoke();
                                }
                                SetCrrentNum(currentNum);
                            }
                        }
                         if(isDeleteBackupPhoto)
                        {
                            orderbagList = enty.Tb_OrderBag_BK.Where(o => o.OrderTime <= endTime&&o.OrderTime >=startTime).ToList();
                            SetTotalNum(orderbagList.Count);
                            int currentNum = 0;
                            foreach (var orderbag in orderbagList)
                            {
                                currentNum++;
                                showNotifyMsgHander.Invoke("正在删除订单:" + orderbag.OrderBagId + "......");

                                if (!orderbag.orderInfo_BK.IsLoaded)
                                {
                                    orderbag.orderInfo_BK.Load();
                                }
                                initProcessBar.Invoke(orderbag.orderInfo_BK.Count);

                                foreach (var orderInfo in orderbag.orderInfo_BK)
                                {

                                    DeletePhotoBackup(orderInfo.OrderPath);
                                    refreshStatusHander.Invoke();
                                }
                                SetCrrentNum(currentNum);
                            }

                        }
                    }

                    if (isDeleteInnerReturn)
                    {
                        List<NewInnerReturn_BK> innerReturn = enty.NewInnerReturn_BK.Where(n => n.CreateTime <= dtEnd.DateTime&&n.CreateTime>=startTime).ToList();
                        initProcessBar.Invoke(innerReturn.Count);
                        SetTotalNum(innerReturn.Count);
                        int currentnum = 0;
                        foreach (var item in innerReturn)
                        {
                            showNotifyMsgHander.Invoke("正在删除内部返单记录:" + item.InnerReturnID);
                            currentnum++;
                            try
                            {
                                enty.DeleteObject(item);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除内部返单记录" + item.InnerReturnID + "出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(currentnum);
                        }
                    }
                    if (isDeleteChatMessage)
                    {

                        List<Messages> messages = enty.Messages.Where(m => m.MessageTime <= dtEnd.DateTime&&m.MessageTime>=startTime).ToList();
                        initProcessBar.Invoke(messages.Count);
                        SetTotalNum(messages.Count);
                        int current = 0;
                        foreach (var item in messages)
                        {
                            current++;
                            showNotifyMsgHander.Invoke("正在删除聊天记录:" + item.Id);
                            try
                            {
                                enty.DeleteObject(item);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除聊天记录" + item.Id + "出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(current);
                        }

                    }
                }

                showNotifyMsgHander.Invoke("删除完成。");
                th.Abort();
                th.Join();
            }
            catch (Exception ex)
            {
                if(!(ex is ThreadAbortException))
                showErrMsgHander.Invoke(ex.Message);
            }
            return ret;
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private int DeletePhotoFolder(string path)
        {
            int ret = 0;
            try
            {
                Directory.Delete(path, true);
            }
            catch(Exception ex)
            {
                showErrMsgHander.Invoke(ex.Message.Replace("\r\n","")+"  请手动删除文件夹：" + path  );
                ret = 1;
            }

            return ret;
        }

        private int DeletePhotoBackup(string path)
        {
            int ret = 0;
            try
            {
                Directory.Delete(path + "\\Backup", true);
            }
            catch (Exception ex)
            {
                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  请手动删除文件夹：" + path);
                ret = 1;
            }

            return ret;
        }

        private int DeleteOrder(int orderbagId)
        {
            int ret = 0;

            return ret;

        }

        #endregion

        #region 删除大板数据
        private void btnDeleteBoardOK_Click(object sender, EventArgs e)
        {
            if (dtBoard.DateTime.ToString() != "0001-1-1 0:00:00")
            {
                if (DialogResult.OK == MessageBox.Show("确定删除" + dtBoard.DateTime.ToString() + "之前的大板数据吗?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    frmStatus = new FrmStatus();
                    frmStatus.controlThreadHander = new ControlThreadHander(ControlThread);
                    frmStatus.Show();
                    th = new Thread(new ThreadStart(CleanupBoardTheadStart));
                    th.Start();

                }
            }
        }


        private void CleanupBoardTheadStart()
        {
            showErrMsgHander = new ShowErrMsgHander(frmStatus.ShowErrMsg);
            refreshStatusHander = new RefreshStatusHander(frmStatus.SetProcessBar);
            showNotifyMsgHander = new ShowNotifyMsgHander(frmStatus.ShowNotifyMsg);
            initProcessBar = new InitProcessBar(frmStatus.InitProcessBar);
            CleanupBoardData(dtBoard.DateTime);
        }

        private void CleanupBoardData(DateTime dt)
        {
            try
            {
                using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
                {
                    int boardstatus = (int)EnumBoardStatus.Printed;

                    List<Board> boardList = enty.Board.Where(b => b.createTime <= dt && b.status == boardstatus).ToList();
                    initProcessBar.Invoke(boardList.Count);
                    SetTotalNum(boardList.Count);
                    int current = 0;
                    foreach (var board in boardList)
                    {
                        current++;
                        showNotifyMsgHander.Invoke("正在删除大板" + board.BoardId);
                        int ret = DeleteBigPic(board.picPath);
                        if (ret == 0)
                        {
                            try
                            {
                                enty.DeleteObject(board);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除大图记录出错 ");
                            }
                        }
                        refreshStatusHander.Invoke();
                        SetCrrentNum(current);
                    }
                }

                showNotifyMsgHander.Invoke("删除大板数据完成。");
                th.Abort();
                th.Join();
            }
            catch (Exception ex)
            {
                if (!(ex is ThreadAbortException))
                showErrMsgHander.Invoke(ex.Message);
            }
 
        }

        private int DeleteBigPic(string path)
        {
            int ret = 0;
            try
            {
                File.Delete(path);
            }
            catch (Exception ex)
            {
                ret = 1;
                showErrMsgHander.Invoke(ex.Message.Replace("\r\n","")+"  请手动删除：" + path);
            }
            return ret;
        }
        #endregion


        #region 财务数据删除
        private void btnFinanceOK_Click(object sender, EventArgs e)
        {
            if (dtFinance.DateTime.ToString() != "0001-1-1 0:00:00")
            {
                if (DialogResult.OK == MessageBox.Show("确定删除" + dtFinance.DateTime.ToString() + "之前的财务数据吗?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    frmStatus = new FrmStatus();
                    frmStatus.controlThreadHander = new ControlThreadHander(ControlThread);
                    frmStatus.Show();
                    th = new Thread(new ThreadStart(CleanupFinanceTheadStart));
                    th.Start();

                }
            }

        }

        private void CleanupFinanceTheadStart()
        {
            showErrMsgHander = new ShowErrMsgHander(frmStatus.ShowErrMsg);
            refreshStatusHander = new RefreshStatusHander(frmStatus.SetProcessBar);
            showNotifyMsgHander = new ShowNotifyMsgHander(frmStatus.ShowNotifyMsg);
            initProcessBar = new InitProcessBar(frmStatus.InitProcessBar);
            CleanupFinanceData(dtFinance.DateTime,chkShopBill.Checked,chkOutShopBill.Checked,chkEmployeePerformance.Checked,chkPaperInfo.Checked,chkShopBlanceCrushRecord.Checked,chkAccountAlarmMsg.Checked);
        }

        private void CleanupFinanceData(DateTime dt, bool isdeleteShopBill, bool isdeleteOutShopBill, bool isdeleteEmployeePerformance, bool isdeletePaperInfo, bool isdeleteShopBlanceCrushRecord, bool isdeleteAccountAlarmMsg)
        {
            try
            {
                using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
                {
                    if (isdeleteShopBill)
                    {
                        int status = (int)ShopBillStatus.CheckedOut;
                        List<SHOP_Bill> shopBillList = enty.SHOP_Bill.Where(s => s.CreateTime <= dt&&s.Status==status).ToList();
                        initProcessBar.Invoke(shopBillList.Count);
                        SetTotalNum(shopBillList.Count);
                        int current = 0;
                        foreach (var shopbill in shopBillList)
                        {
                            current++;
                            showNotifyMsgHander.Invoke("正在删除商户账单" + shopbill.BillId);
                            try
                            {
                                enty.DeleteObject(shopbill);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除商户账单" + shopbill.BillId + "出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(current);

                        }
                    }
                    if (isdeleteOutShopBill)
                    {
                        int status = (int)OutProcessPayStatus.Complete;
                        List<OutShop_Bill> shopBillList = enty.OutShop_Bill.Where(s => s.CreateTime <= dt&&s.PayStatus==status).ToList();
                        initProcessBar.Invoke(shopBillList.Count);
                        SetTotalNum(shopBillList.Count);
                        int current = 0;
                        foreach (var shopbill in shopBillList)
                        {
                            current++;
                            showNotifyMsgHander.Invoke("正在删除委外商户账单" + shopbill.BillID);
                            try
                            {
                                enty.DeleteObject(shopbill);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除委外商户账单" + shopbill.BillID + "出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(current);
                        }

                    }
                    if (isdeleteShopBlanceCrushRecord)
                    {

                        List<ShopBlanceCrushRecord> list = enty.ShopBlanceCrushRecord.Where(s => s.CrushTime <= dt).ToList();
                        initProcessBar.Invoke(list.Count);
                        SetTotalNum(list.Count);
                        int current = 0;
                        foreach (var item in list)
                        {
                            current++;
                            showNotifyMsgHander.Invoke("正在删除商户充值记录" + item.ShopBlanceCrushRecordId);
                            try
                            {
                                enty.DeleteObject(item);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除商户充值记录" + item.ShopBlanceCrushRecordId + "出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(current);
                        }
                    }
                    if (isdeleteAccountAlarmMsg)
                    {

                        List<AccountAlarmMsg> list = enty.AccountAlarmMsg.Where(s => s.AlarmTime <= dt).ToList();
                        initProcessBar.Invoke(list.Count);
                        int current = 0;
                        foreach (var item in list)
                        {
                            current++;
                            showNotifyMsgHander.Invoke("正在删除账户报警记录" + item.Id);
                            try
                            {
                                enty.DeleteObject(item);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除账户报警记录" + item.Id + "出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(current);
                        }
                    }
                    if (isdeleteEmployeePerformance)
                    {

                        List<New_EmployeePerformance_BK> list = enty.New_EmployeePerformance_BK.Where(s => s.TechCompletedTime <= dt).ToList();
                        initProcessBar.Invoke(list.Count);
                        SetTotalNum(list.Count);
                        int current = 0;
                        foreach (var item in list)
                        {
                            current++;
                            showNotifyMsgHander.Invoke("正在删除员工业绩记录" + current);
                            try
                            {
                                enty.DeleteObject(item);
                                enty.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除员工业绩记录出错");
                            }
                            refreshStatusHander.Invoke();
                            SetCrrentNum(current);

                        }
                    }
                    if (isdeletePaperInfo)
                    {

                        List<PaperInfo> list = enty.PaperInfo.Where(s => s.AddTime <= dt).ToList();
                        try
                        {
                            initProcessBar.Invoke(list.Count);
                            SetTotalNum(list.Count);
                            int current = 0;
                            foreach (var item in list)
                            {
                                current++;
                                showNotifyMsgHander.Invoke("正在删除相纸记录" + item.PrintPaperId);
                                //1删除相纸浪费表
                                if (!item.PaperWasteRecords.IsLoaded)
                                {
                                    item.PaperWasteRecords.Load();
                                }
                                List<PaperWasteRecords> paperwasterecords = item.PaperWasteRecords.ToList();
                                foreach (var paperwaste in paperwasterecords)
                                {
                                    try
                                    {

                                        enty.DeleteObject(paperwaste);
                                        enty.SaveChanges();
                                    }
                                    catch (Exception ex)
                                    {
                                        showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除相纸浪费记录" + paperwaste.Id + "出错");
                                    }

                                }

                                //删除关联的board表
                                if (!item.Board.IsLoaded)
                                {
                                    item.Board.Load();
                                }
                                List<Board> boardList = item.Board.ToList();
                                foreach (var board in boardList)
                                {
                                    DeleteBigPic(board.picPath);
                                    try
                                    {
                                        enty.DeleteObject(board);
                                        enty.SaveChanges();
                                    }
                                    catch (Exception ex)
                                    {
                                        showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除大板记录" + board.BoardId + "出错");
                                    }

                                }

                                try
                                {
                                    enty.DeleteObject(item);
                                    enty.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    showErrMsgHander.Invoke(ex.Message.Replace("\r\n", "") + "  删除相纸记录" + item.PrintPaperId + "出错");
                                }
                                refreshStatusHander.Invoke();
                                SetCrrentNum(current);
                            }

                        }
                        catch (Exception ex)
                        {
                            if (!(ex is ThreadAbortException))
                            showErrMsgHander.Invoke(ex.Message);

                        }
                    }


                }

                showNotifyMsgHander.Invoke("删除完成。");
                th.Abort();
                th.Join();
            }
            catch (Exception ex)
            {
                if (!(ex is ThreadAbortException))
                showErrMsgHander.Invoke(ex.Message);
            }
        }
        #endregion


        private void SetTotalNum(int num)
        {
            SetTotalNumHander settotal = new SetTotalNumHander(frmStatus.SetTotalNum);
            this.Invoke(settotal, new object[] { num });
        }

        private void SetCrrentNum(int num)
        {
            SetCurrentNumHander setcurrent = new SetCurrentNumHander(frmStatus.SetCurrentNum);
            this.Invoke(setcurrent, new object[] { num });
        }
        private void ControlThread(bool isStart)
        {
            if (!isStart)
            {
                th.Abort();
                //th.Join();
            }

        }

        private void chkOrder_CheckStateChanged(object sender, EventArgs e)
        {
            if (chkOrder.Checked)
            {
                chkOrderPhoto.CheckState = CheckState.Checked;
                chkPhotoBackup.CheckState = CheckState.Checked;
                chkOrderPhoto.Enabled = false;
                chkPhotoBackup.Enabled = false;
            }
            else
            {
                chkOrderPhoto.CheckState = CheckState.Unchecked;
                chkPhotoBackup.CheckState = CheckState.Unchecked;
                chkOrderPhoto.Enabled = true;
                chkPhotoBackup.Enabled = true;
            }
        }

        private void chkOrderPhoto_CheckedChanged(object sender, EventArgs e)
        {
            if (chkOrderPhoto.Checked)
            {
                chkPhotoBackup.CheckState = CheckState.Checked;
                chkPhotoBackup.Enabled = false;
            }
            else
            {
                chkPhotoBackup.CheckState = CheckState.Unchecked;
                chkPhotoBackup.Enabled = true;
            }
        }

        //private void CleanupFileTheadStart()
        //{
        //    showErrMsgHander = new ShowErrMsgHander(frmStatus.ShowErrMsg);
        //    refreshStatusHander = new RefreshStatusHander(frmStatus.SetProcessBar);
        //    showNotifyMsgHander = new ShowNotifyMsgHander(frmStatus.ShowNotifyMsg);
        //    initProcessBar = new InitProcessBar(frmStatus.InitProcessBar);
        //    CleanupBoardData(dtBoard.DateTime);
        //}
        private void simpleButtonCleanFile_Click(object sender, EventArgs e)
        {
           
             DateTime endTime = dtDelFileEndTime.DateTime;
             if (DialogResult.Yes == MessageBox.Show("确定要删除" + endTime.ToString("yyyy-MM-dd") + "之前的已开单文件吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
             {
                 if (DateTime.Now < endTime)
                 {
                     if (DialogResult.Yes != MessageBox.Show("您选定的时间比当前时间还有提前，要继续吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                         return;
                 }
                 if ((DateTime.Now - endTime).Days <= 15)
                 {
                     if (DialogResult.Yes != MessageBox.Show("您选定的时间与当前时间的差距在15天之内，要继续吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                         return;
                 }
             }
            frmStatus = new FrmStatus();
            frmStatus.controlThreadHander = new ControlThreadHander(ControlThread);
            frmStatus.Show();
            th = new Thread(new ThreadStart(CleanupFileTheadStart));
            th.Start();

           
        }
        public void CleanupFileTheadStart()
        {
            try
            {
                showErrMsgHander = new ShowErrMsgHander(frmStatus.ShowErrMsg);
                refreshStatusHander = new RefreshStatusHander(frmStatus.SetProcessBar);
                showNotifyMsgHander = new ShowNotifyMsgHander(frmStatus.ShowNotifyMsg);
                initProcessBar = new InitProcessBar(frmStatus.InitProcessBar);
               
                    //不删数据库的产品记录
                    //Cursor = Cursors.WaitCursor;
                    string totalPath = "";
                    using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                    {
                        FileDirPath fd = db.FileDirPath.FirstOrDefault(p => p.id == 2);
                        if (fd != null)
                        {
                            totalPath = fd.FileDir;
                        }
                    }
                    DelDirectory(totalPath, dtDelFileEndTime.DateTime, checkBoxBackUP.Checked);
                    /*
                    //要删数据库的产品记录
                    List<string> orderInfoDirectorys = RDBLL.GetDelPaths(endTime);
                    DelDirectorys(orderInfoDirectorys);*/
                    //if (th.ThreadState != ThreadState.Aborted)
                    //{
                    //    th.Abort();
                    //}
                    
                  
                //}\\
            }
            catch (Exception ex)
            {
                //Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //删除目录的方法
        public void DelDirectory(string direcoty, DateTime endTime,bool isBack)
        {
            string[] shopPaths = Directory.GetDirectories(direcoty);
            initProcessBar.Invoke(shopPaths.Length);
            int current = 0;
            foreach (string shopPath in shopPaths)
            {
                current++;
                SetTotalNum(shopPaths.Length);
               
                string[] timePaths = Directory.GetDirectories(shopPath);
                foreach (string timePath in timePaths)
                {
                    try
                    {
                        DateTime time = Convert.ToDateTime(timePath.Substring(timePath.LastIndexOf("\\") + 1));
                        if (time < endTime)
                        {
                            if (isBack)
                            {
                                showNotifyMsgHander.Invoke("正在删除文件夹" + timePath+"中的backup文件");
                                DeleBackUpFolder(timePath);
                            }
                            else
                            {

                                showNotifyMsgHander.Invoke("正在删除文件夹" + timePath);
                                Directory.Delete(timePath, true);
                            }
                           
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                refreshStatusHander.Invoke();
                SetCrrentNum(current);
            }
            showNotifyMsgHander.Invoke("清理工作结束，您现在可以退出！");
            //MessageBox.Show("指定的已开单文件已成功清理！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        public void DeleBackUpFolder(string root)
        {
            DirectoryInfo dirInfo=new DirectoryInfo(root);
            List<DirectoryInfo> dirArr = dirInfo.GetDirectories().ToList();
            foreach (DirectoryInfo dir in dirArr)
            {
                if (dir.GetDirectories().Count() > 0)
                {
                    DeleBackUpFolder(dir.FullName);
                }
                else if (dir.FullName.EndsWith("Backup"))
                {
                    showNotifyMsgHander.Invoke("正在删除文件夹" + dir.FullName + "中的backup文件");
                    dir.Delete(true);
                }
            }
 
        }

        private void btntransferData_Click(object sender, EventArgs e)
        {
            if (dtTransfer.DateTime.ToString() != "0001-1-1 0:00:00")
            {
                if (DialogResult.OK == MessageBox.Show("确定转移" + dtTransfer.DateTime.ToString() + "之前的员工业绩数据吗?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    bwTransferData.RunWorkerAsync();
                }
            }

        }

        public void TransferEmployeeStatisticsData(BackgroundWorker worker,DoWorkEventArgs e)
        {
            //try
            //{
            //    Cursor = Cursors.WaitCursor;
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    int currentnum = 0;

                    List<New_EmployeePerformance> list = db.New_EmployeePerformance.Where(s => s.TechCompletedTime <= dtTransfer.DateTime).ToList();
                    int count =list.Count;
                    for (int i = 0; i < list.Count; i++)
                    {
                        New_EmployeePerformance_BK emp_bk = new New_EmployeePerformance_BK()
                        {
                            CtmName =list[i].CtmName,
                            MultiplePageNum =list[i].MultiplePageNum,
                            OrderArea =list[i].OrderArea,
                            OrderConpletedTime =list[i].OrderConpletedTime,
                            OrderCount =list[i].OrderCount,
                            OrderCreateTime =list[i].OrderCreateTime,
                            OrderPath =list[i].OrderPath,
                            OrderproductId =list[i].OrderproductId,
                            OrderProductName =list[i].OrderProductName,
                            PhotoTotalNum =list[i].PhotoTotalNum,
                            PreOrderAreas =list[i].PreOrderAreas,
                            ProductPhotoNum =list[i].ProductPhotoNum,
                            ReceivedTime =list[i].ReceivedTime,
                            ShopName =list[i].ShopName,
                            SinglePageNum =list[i].SinglePageNum,
                            Status =list[i].Status,
                            TechCompletedTime =list[i].TechCompletedTime,
                            TechId =list[i].TechId,
                            UserId =list[i].UserId
                        };
                        db.AddToNew_EmployeePerformance_BK(emp_bk);
                        db.DeleteObject(list[i]);
                        db.SaveChanges();
                        currentnum++;
                        int percentComplete =currentnum/count*100;
                        worker.ReportProgress(percentComplete);
                        
                    }

                }
               
              
            //}
            //catch (Exception ex)
            //{

            //    throw ex;
            //}
            //finally
            //{
            //    Cursor = Cursors.Default;
            //}
        }

        private void bwTransferData_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            TransferEmployeeStatisticsData(worker, e);
        }

        private void bwTransferData_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBarTransferemployeeStatistics.Value = e.ProgressPercentage;
        }

        private void bwTransferData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("员工业绩转移完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string gridnamesText=textBoxGridNames.Text.Trim().Trim(',');
            if(string.IsNullOrEmpty(gridnamesText))
            {
                return ;
            }
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                GridSubArea area = (GridSubArea)comboBoxSubArea.SelectedItem;
                List<Grid> gridList = db.Grid.Where(g => g.GridSubArea.SubAreaID == area.SubAreaID).ToList();
                string headName = gridList.OrderBy(o=>o.GridName).FirstOrDefault().GridName.Substring(0,1);
                string[] names = gridnamesText.Split(',');
                foreach (string name in names)
                {
                    string gridName = headName + name;
                    Grid g = db.Grid.FirstOrDefault(gr=>gr.GridName==gridName);
                    if (false != null)
                    {
                        g.Status = 0;
                        g.SomeId = 0;
                    }
                }
                db.SaveChanges();
 
            }
            MessageBox.Show("更新完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void xtraTabControl1_TabIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (xtraTabControl1.SelectedTabPage.Name == "xtraTabPageGrid")
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    List<GridSubArea> listGrid = db.GridSubArea.Where(p => p.Type == 0).ToList();
                    comboBoxSubArea.DataSource = listGrid;
                    comboBoxSubArea.DisplayMember = "SubAreaID";
                    comboBoxSubArea.ValueMember = "SubAreaName";

                }
            }
        }

    }
}
